/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.module.web;

import org.apache.commons.lang3.StringUtils;
import org.pajamas.starter.core.ex.AbstractPajamasChkException;
import org.pajamas.starter.core.ex.AbstractPajamasRunException;
import org.pajamas.starter.core.vo.PajamasValidationException;
import org.pajamas.starter.core.vo.ResultVo;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;

import lombok.extern.slf4j.Slf4j;

/**
 * @author william
 * @since 2024/1/14
 */
@RestControllerAdvice
@Slf4j
public class PajamasExceptionHandlerAdvice {
    @ExceptionHandler(PajamasValidationException.class)
    public ResultVo validationExceptionHandle(PajamasValidationException ex, HttpServletResponse response) {
        response.setStatus(this.extractHttpStatus(ex).value());
        String multiErrMsg = ex.getViolations()
                .stream()
                .filter(Objects::nonNull)
                .map(ConstraintViolation::getMessage)
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.joining(";"));
        return ResultVo
                .builder()
                .payload(multiErrMsg)
                .build();
    }

    @ExceptionHandler(Exception.class)
    public ResultVo globalExceptionHandle(Exception ex, HttpServletResponse response) {
        Throwable realEx = ex instanceof UndeclaredThrowableException ?
                ((UndeclaredThrowableException) ex).getUndeclaredThrowable() : ex;
        log.error("globalExceptionHandle.realEx.msg:[{}]", realEx.getMessage());
        response.setStatus(this.extractHttpStatus(realEx).value());
        return ResultVo
                .builder()
                .payload(realEx.getMessage())
                .build();
    }

    private HttpStatus extractHttpStatus(Throwable throwable) {
        HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        if (throwable instanceof AbstractPajamasRunException) {
            httpStatus = ((AbstractPajamasRunException) throwable).getHttpStatus();
        } else if (throwable instanceof AbstractPajamasChkException) {
            httpStatus = ((AbstractPajamasChkException) throwable).getHttpStatus();
        }
        return httpStatus;
    }
}
